package org.igeek.config.InstantiationAwareBeanPostProcessor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

/**
 * @package org.igeek.config.InstantiationAwareBeanPostProcessor
 * @Description 动态代理
 * @Author LittlePunk [296526219@qq.ccom]
 * @Version 2022.1
 * @Date 2023/11/14 20:33
 */
//@Component
public class JDKProxy {
    //创建目标对象
    private Object target;


    private Object proxy = null;

    public JDKProxy() {
    }

    public JDKProxy(Object target) {
        this.target = target;
    }

    //获取代理对象
    public Object getProxy(){
        //声明代理对象

        //创建handler处理器
        InvocationHandler handler = new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //获取当前方法名
                String methodName = method.getName();
                //开启日志追踪
                System.out.println("开始日志追踪:method=" + methodName + ",args=" + Arrays.toString(args));
                long start = System.currentTimeMillis();
                //执行核心方法
                Object result = method.invoke(target, args);
                //结束日志追踪
                long end = System.currentTimeMillis();
                System.out.println("结束日志追踪:method=" + methodName + ",耗时=" + (end - start) + ",执行结果=" + result);
                return null;
            }
        };
        //获取类加载器
        ClassLoader classLoader = target.getClass().getClassLoader();
        //获取接口方法
        Class<?>[] interfaces = target.getClass().getInterfaces();
        //创建代理对象
        proxy = Proxy.newProxyInstance(classLoader,interfaces,handler);
        return proxy;
    }
}
